<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="单据类型" prop="docType">
            <el-select v-model="dataForm.docType" placeholder="单据类型" @change="docTypeChange">
              <el-option v-for="item in docTypeArr" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批段模版名称" prop="templateName">
            <el-input v-model="dataForm.templateName" placeholder="审批段模版名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注" type="textarea"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-button type="primary" style="margin-bottom: 10px" @click="handleClickAdd">添加审批段</el-button>
      <el-table :data="swfDocPhaseDefDTOList" border>
        <el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
        <el-table-column label="审批段名称" prop="phaseName" header-align="center" align="center">
          <template v-slot="scope">
            <el-select v-model="scope.row.phaseId" placeholder="审批段名称" @change="selectChange('phase', scope.row)">
              <el-option v-for="item in PhaseNameDefList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="审批人" prop="aprvUserId" header-align="center" align="center">
          <template v-slot="scope">
            <el-select v-model="scope.row.aprvUserId" placeholder="审批人" @change="selectChange('user', scope.row)">
              <el-option v-for="item in userList" :key="item.id" :value="item.id" :label="item.realName"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="是否终审" prop="isLastAprv" header-align="center" align="center">
          <template v-slot="scope">
            <el-radio-group v-model="scope.row.isLastAprv">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" header-align="center" align="center">
          <template v-slot="scope">
            <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="100">
          <template v-slot="scope">
            <el-button type="primary" link @click="deleteClick(scope.$index)">{{ $t("delete") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const docTypeArr = ref<any>([]);
const PhaseNameDefList = ref<any>([]);
const userList = ref<any>([]);

const dataForm = reactive({
  id: "",
  docType: "",
  docTypeName: "",
  remark: "",
  templateName: ""
});

const swfDocPhaseDefDTOList = ref<any>([]);

const rules = ref({
  docType: [{ required: true, message: "请选择单据类型", trigger: "change" }],
  templateName: [{ required: true, message: "请输入审批段模版名称", trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  getDicType();
  getPhaseNameDefList();
  getUserList();

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/swfPhaseTemplate/swfphasetemplate/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    dataForm.docType = dataForm.docType + "";
    swfDocPhaseDefDTOList.value = res.data.swfDocPhaseDefDTOList;
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  console.log(swfDocPhaseDefDTOList.value);
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/swfPhaseTemplate/swfphasetemplate", { ...dataForm, swfDocPhaseDefDTOList: swfDocPhaseDefDTOList.value }).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

// 获取审批段名称
const getPhaseNameDefList = () => {
  baseService.post("swfPhaseNameDef/swfphasenamedef/getList").then((res) => {
    PhaseNameDefList.value = res.data;
  });
};

// 获取审批人
const getUserList = () => {
  baseService.get("sys/user/list").then((res) => {
    userList.value = res.data;
  });
};

// 获取单据列表
const getDicType = () => {
  baseService.post("sys/dict/data/getDictDataList", { dictType: "approveStep" }).then((res) => {
    docTypeArr.value = res.data;
  });
};

const docTypeChange = () => {
  const idx = docTypeArr.value.findIndex((item: any) => item.dictValue === dataForm.docType);
  dataForm.docTypeName = docTypeArr.value[idx].dictLabel;
};

const deleteClick = (index: number) => {
  swfDocPhaseDefDTOList.value.splice(index, 1);
  swfDocPhaseDefDTOList.value.map((item: any, index: number) => {
    item.sortNum = index + 1;
  });
};

const handleClickAdd = () => {
  swfDocPhaseDefDTOList.value.push({
    sortNum: swfDocPhaseDefDTOList.value.length + 1,
    phaseName: "",
    aprvUserId: "",
    isLastAprv: 0,
    remark: ""
  });
};

const selectChange = (type: string, row: any) => {
  let idx = null;
  switch (type) {
    case "phase":
      idx = PhaseNameDefList.value.findIndex((item: any) => item.id === row.phaseId);
      row["phaseName"] = PhaseNameDefList.value[idx].name;
      break;
    case "user":
      idx = userList.value.findIndex((item: any) => item.id === row.aprvUserId);
      row["aprvUser"] = userList.value[idx].realName;
      break;
  }
};

defineExpose({
  init
});
</script>
